package com.newcapec.modules.iot.service;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.*;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

@Service
public class IotService {
    private static String PROXY_ADDRESS;
    private static String PROXY_ENABLE = "0";

    public static PoolingHttpClientConnectionManager manager = new PoolingHttpClientConnectionManager();

    public static HttpClient HTTP_CLIENT = HttpClients.custom().setConnectionManager(manager).build();

    public String mkHeaderFromIOT(String loginurl,String username,String password) throws Exception {
        HttpEntity entity = null;
        String responseData = null;

        String header = "Bearer ";
        Map<String, String> map = new HashMap<String, String>();
        map.put("username", username);
        map.put("password", password);
        Gson g = new Gson();
        String requestStr = g.toJson(map);
        HttpPost httpPost = new HttpPost(loginurl);
        RequestConfig requestConfig = setConfiguration(30000, 15000, 60000);
        httpPost.setConfig(requestConfig);
        // 封装请求内容
        httpPost.addHeader("Content-type", "application/json; charset=UTF-8");
        boolean isHeaderNull = (header == null || "".equals(header));
        if (!isHeaderNull) {
            httpPost.addHeader("X-Authorization", header);
        }
        StringEntity strEntity = new StringEntity(requestStr, "UTF-8");
        // 设置请求内容
        httpPost.setEntity(strEntity);

        HttpResponse response = null;
        entity = null;
        responseData = null;
        // 发送请求
        response = HTTP_CLIENT.execute(httpPost);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != 200) {
            // 获取应答数据
            entity = response.getEntity();
            InputStream is = entity.getContent();
            Header encodingHeader = entity.getContentEncoding();
            Charset contentEncoding = encodingHeader == null ? Consts.UTF_8 : Charset.forName(encodingHeader.getValue());

            BufferedReader reader = new BufferedReader(new InputStreamReader(is, contentEncoding));
            responseData = IOUtils.toString(reader);
           /* LOGGER.error("sendHttpRequestJsonIOT请求失败,请求地址：{}，请求数据:{}, 返回错误代码:{}, responseData:{}",
                    url,requestData,statusCode, responseData);*/
            //errString.append("sendHttpRequestJsonIOT请求失败,返回错误代码:"+statusCode+" responseData:"+responseData);
            httpPost.abort();

            JSONObject jsonData = JSONObject.parseObject(responseData);
            String errorCode = jsonData.containsKey("errorCode") ? jsonData.getString("errorCode") : "-1";

            //recordException("sendHttpRequestJsonIOT", url, jsonData.toString());

            String status = jsonData.get("status").toString();
            int statusInt = Integer.parseInt(status);
            // -400 代表特殊老物联网版本的401(Token失效)错误代码
            if (400 == statusInt && "11".equals(errorCode)) {
                statusCode = -400;
                jsonData.put("status", statusCode);
            }
            return null;
        }
        // royleexh 2015年7月9日 10:28:08 将应答放入
        //HTTPRESPONSETHREADLOCAL.set(response);

        // 请求成功结果处理
        //LOGGER.debug("StatusLine:{}", response.getStatusLine());
        // 获取应答数据
        entity = response.getEntity();
        InputStream is = entity.getContent();
        Header encodingHeader = entity.getContentEncoding();
        Charset contentEncoding = encodingHeader == null ? Consts.UTF_8 : Charset.forName(encodingHeader.getValue());

        BufferedReader reader = new BufferedReader(new InputStreamReader(is, contentEncoding));
        return header+IOUtils.toString(reader);
    }


    private static RequestConfig setConfiguration(int socketTimeout, int connTimeout, int connReqTimeout) {
        RequestConfig config = null;
        if ("1".equals(PROXY_ENABLE)) {
            if (StringUtils.isNotBlank(PROXY_ADDRESS)) {
                HttpHost proxy = new HttpHost(PROXY_ADDRESS.split(":")[0], Integer.valueOf(PROXY_ADDRESS.split(":")[1]));
                config = RequestConfig.custom().setSocketTimeout(socketTimeout).setConnectTimeout(connTimeout)
                        .setConnectionRequestTimeout(connReqTimeout).setProxy(proxy).build();
            } else {
                config = RequestConfig.custom().setSocketTimeout(socketTimeout).setConnectTimeout(connTimeout)
                        .setConnectionRequestTimeout(connReqTimeout).build();
            }
        } else {
            config = RequestConfig.custom().setSocketTimeout(socketTimeout).setConnectTimeout(connTimeout)
                    .setConnectionRequestTimeout(connReqTimeout).build();
        }
        return config;
    }

}
